from rest_framework import serializers

from areas.models import Area
from oauth.models import OAuthQQUser
from users.models import User, Address
from django_redis import get_redis_connection
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from django.conf import settings
import re
from rest_framework_jwt.settings import api_settings


class AreasSerializer(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields = "__all__"


"""

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='addresses', verbose_name='用户')
    title = models.CharField(max_length=20, verbose_name='地址名称')
    receiver = models.CharField(max_length=20, verbose_name='收货人')
    province = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='province_addresses', verbose_name='省')
    city = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='city_addresses', verbose_name='市')
    district = models.ForeignKey('areas.Area', on_delete=models.PROTECT, related_name='district_addresses', verbose_name='区')
    place = models.CharField(max_length=50, verbose_name='地址')
    mobile = models.CharField(max_length=11, verbose_name='手机')
    tel = models.CharField(max_length=20, null=True, blank=True, default='', verbose_name='固定电话')
    email = models.CharField(max_length=30, null=True, blank=True, default='', verbose_name='电子邮箱')
    is_deleted = models.BooleanField(default=False, verbose_name='逻辑删除')
"""


class AddressesSerializer(serializers.ModelSerializer):
    province_id = serializers.IntegerField(min_value=1, write_only=True)
    city_id = serializers.IntegerField(min_value=1, write_only=True)
    district_id = serializers.IntegerField(min_value=1, write_only=True)

    # 序列化返回所指定省市区字段    嵌套序列化返回
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)

    class Meta:
        model = Address
        fields = (
        'title', 'receiver', 'place', 'mobile', 'province_id', 'city_id', 'district_id', 'province', 'city', 'district','id')

    # 验证手机号格式
    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式不正确')

        return value

    def create(self, validated_data):
        # 获取用户对象
        user = self.context['request'].user

        validated_data['user'] = user
        address = Address.objects.create(**validated_data)

        return address

    # def update(self, instance, validated_data):

# class AddressSerialzier(serializers.Serializer):
#     addresses=AddressesSerializer(many=True)
#     default_address_id=serializers.IntegerField()



